package com.spmsys.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.*;

/**
 * DBCP数据库连接池类
 */
public class DBCPDataSource {
    private static final Map<String, DataSource> dataSources = new HashMap<>();

    static {
        JSONArray dbcpPackage = JSONObject.parseArray(FileUtil.readFileByClassLoader(DBCPDataSource.class, "dbcpPackage.json"));
        int size = dbcpPackage.size();
        for (int i = 0; i < size; i++) {
            try (InputStream input = DBCPDataSource.class.getClassLoader().getResourceAsStream(dbcpPackage.getJSONObject(i).getString("value"))) {
                //加载配置
                Properties properties = new Properties();
                properties.load(input);
                //创建数据源对象
                dataSources.put(dbcpPackage.getJSONObject(i).getString("name"), BasicDataSourceFactory.createDataSource(properties));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static DataSource getDataSource(String databaseName) {
        return dataSources.get(databaseName);
    }

    public static Connection getConnection(String databaseName) {
        try {
            return dataSources.get(databaseName).getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
